import { defineStore } from "pinia";
import piniaPersistConfig from "@/stores/helper/persist";
import { EMClient } from "@/IM";
import _ from "lodash";
import { setMessageKey } from "@/views/im/utils/handleSomeData";
import { playRing, isOpenPlayRing } from "@/IM/constant/usePlayRing";
import { useAppStore } from "./app";
import { getUserList, statusList, setStatus } from "@/api/modules/im";
import { ElMessage } from "element-plus";
interface imState {
  userId: string;
  onLine: string | boolean;
  token: string | null;
  chatWith: string;
  contacts: object[];
  userInfo: object;
  historyMessages: object;
  lastMessage: string;
  lastHisId: string;
  usersInfosObj: object;
  onLineStatus: [];
  messageStates: object;
}
export const useImStore = defineStore({
  id: "imState",
  state: (): imState => ({
    userId: "",
    userInfo: {},
    onLine: false, //在线状态
    token: "",
    chatWith: "", //当前聊天人
    contacts: [], //好友列表
    historyMessages: {},
    lastMessage: "", //最新消息id
    lastHisId: "", //最新历史纪录
    usersInfosObj: {}, //用户信息
    onLineStatus: [],
    messageStates: {}
  }),
  getters: {
    getStatus: state => {
      return state.onLine;
    }
  },
  actions: {
    // 重置
    initData() {
      this.contacts = [];
      this.historyMessages = [];
    },
    //设置消息状态
    setMessageStatus(key, value) {
      this.messageStates[key] = value;
    },
    // 登录
    doLogin() {
      if (!useAppStore().$state.imToken || !useAppStore().$state.userId) {
        ElMessage.error("缺少用户信息，无法登录聊天平台");
        return false;
      }
      return EMClient.open({
        username: useAppStore().$state.userId,
        accessToken: useAppStore().$state.imToken
      })
        .then(res => {
          console.log(res);
          return true;
        })
        .catch(err => {
          console.log(err);
          return false;
        });
    },
    //获取系统内当前用户信息
    async getFetchUserInfoById(userId) {
      let infos = await getUserList({
        userIds: [userId || this.userId]
      });
      if (useAppStore().userId !== infos.data[0].userId) {
        this.initData();
      }
      this.userInfo = infos.data[0] || {};
      return this.userInfo;
    },
    //设置token
    setToken(token) {
      this.token = token;
    },
    //设置会话已读
    setChannelRead() {
      let option = {
        chatType: "singleChat",
        type: "channel",
        to: this.chatWith
      };
      const saveMsg = EMClient.Message.create(option);
      EMClient.send(saveMsg);
    },
    getMessageStatus(messages) {
      let arr: any = [];
      messages.map((item: any) => {
        if (item.from == this.userId) {
          arr.push(item.id);
        }
      });
      if (arr.length) {
        statusList({
          mids: arr
        }).then((res: any) => {
          if (res.data) {
            res.data.map(item => {
              this.messageStates[item.messageId] = item.status;
            });
          }
        });
      }
    },
    //获取某个用户的历史纪录
    async getHistoryMessage(options) {
      return new Promise((resolve, reject) => {
        options.targetId = this.chatWith;
        options.chatType = "singleChat";
        options.pageSize = 10;
        EMClient.getHistoryMessages(options)
          .then(res => {
            if (this.chatWith) {
              if (options.cursor == -1) {
                this.historyMessages[this.chatWith] = [];
              }
              this.historyMessages[this.chatWith] = [..._.reverse(res.messages), ...this.historyMessages[this.chatWith]];
              //获取发出去的消息当前状态
              this.getMessageStatus(res.messages);
              // 更新一下最后一条消息
              this.contacts.map((item: any) => {
                if (item.conversationId === this.chatWith) {
                  item.lastMessage = this.historyMessages[this.chatWith][this.historyMessages[this.chatWith].length - 1];
                }
              });
              resolve(res.messages);
            }
          })
          .catch(error => {
            reject(error);
          });
      });
    },
    //收到一条消息
    getAMessage(msg) {
      if (isOpenPlayRing.value) playRing();
      const key = setMessageKey(msg);
      if (!this.historyMessages[key]) {
        this.historyMessages[key] = [];
        //没有历史消息就没有会话，需要刷新本地会话
        console.log("新会话", key);
        this.getContacts();
      }
      this.historyMessages[key].push(msg);
      this.updateConversations({
        conversationId: key,
        chatType: msg.chatType
      });
    },
    //删除一条消息
    deleteAmessage(msg, add) {
      const key = setMessageKey(msg);
      this.historyMessages[key] = this.historyMessages[key].filter(item => {
        return item.id !== msg.id;
      });
      if (add) {
        this.getAMessage(msg);
      }
      this.updateConversations({
        conversationId: key,
        chatType: msg.chatType
      });
    },
    //获取联系人（现在是获取本地会话列表）
    getContacts() {
      this.getConversations();
    },
    //删除联系人（现在是删除某个本地会话列表））
    async deleteContacts(id) {
      return new Promise((resolve, reject) => {
        let options = {
          // 会话 ID：单聊为对方的用户 ID，群聊为群组 ID。
          conversationId: id,
          conversationType: "singleChat",
          isRemoveLocalMessage: true
        };
        EMClient.localCache
          .removeLocalConversation(options)
          .then(res => {
            this.unSubFriendsPresence(this, id);
            this.getContacts(); //这里可以直接删除，不用重新获取，todo
            resolve(true);
          })
          .catch(e => {
            reject(false);
          });
      });
    },
    //获取本地某个本地会话并匹配系统联系人信息
    async getConversation(id) {
      let conversationList: object[] = [];
      const result = await EMClient.localCache.getLocalConversation({
        conversationType: "singleChat",
        conversationId: id
      });
      let hasData = false;
      this.contacts.map((item: any) => {
        if (item.conversationId === id) {
          hasData = true;
          result.data = item;
        }
      });
      if (!hasData) {
        return getUserList({
          userIds: [id]
        }).then((infos: any) => {
          if (!infos.data[0]) return;
          this.subFriendsPresence(this, [id]);
          infos.data[0].conversationId = id;
          conversationList = [Object.assign(infos.data[0], result.data || {})];
          this.contacts = [...this.contacts, ...conversationList];
          return Object.assign(infos.data[0], result.data || {});
        });
      } else {
        return result.data;
      }
    },
    //获取所有本地会话并匹配系统联系人信息
    async getConversations(pageSize = 50, cursor = "") {
      let conversationList: object[] = [];
      const result = await EMClient.localCache.getLocalConversations();
      if (result.data.length) {
        conversationList = [...result.data];
      } else {
        //默认只取50条远端数据数据，实际可自行加载更多。
        const result = await EMClient.getServerConversations({
          pageSize,
          cursor
        });
        if (result.data?.conversations?.length) {
          conversationList = [...result.data.conversations];
        }
      }
      let userIds: string[] = [];
      conversationList.map((item: any) => {
        userIds.push(item.conversationId);
      });
      getUserList({
        userIds: userIds
      }).then((infos: any) => {
        conversationList = conversationList.map((conversation: any) => {
          infos.data.map(info => {
            if (info.userId === conversation.conversationId) {
              conversation = Object.assign(info, conversation);
            }
          });
          return conversation;
        });
        if (this.contacts.length && cursor) {
          this.contacts = [...this.contacts, ...conversationList];
        } else {
          this.contacts = conversationList;
        }
        //订阅在线状态
        this.subFriendsPresence(this, userIds);
      });
    },
    //更新本地会话列表，历史已存在的刷新，不存在的匹配系统用户信息
    async updateConversations(params) {
      const { conversationId, chatType } = params;
      try {
        const result = await EMClient.localCache.getLocalConversation({
          conversationId,
          conversationType: chatType
        });
        if (!result?.data) return;
        const toBeUpdateConversationItem = { ...result?.data };
        //如果删除了最后一条消息就更新最后一条消息
        let lastIndex = -1;
        this.historyMessages[conversationId].map((item, index) => {
          if (item.id === toBeUpdateConversationItem.lastMessage?.serverMsgId) {
            lastIndex = index;
          }
        });
        if (lastIndex < 0) {
          toBeUpdateConversationItem.lastMessage =
            this.historyMessages[conversationId][this.historyMessages[conversationId].length - 1];
        }
        const _index = this.contacts.findIndex((c: any) => {
          return c.conversationId === toBeUpdateConversationItem.conversationId;
        });
        if (_index > -1) {
          let newConversation = Object.assign(this.contacts[_index], toBeUpdateConversationItem);
          this.contacts.splice(_index, 1);
          this.contacts.unshift(newConversation);
        } else {
          getUserList({
            userIds: [conversationId]
          }).then((infos: any) => {
            let newConversation = toBeUpdateConversationItem;
            if (infos.data && infos.data.length) {
              newConversation = Object.assign(infos.data[0], toBeUpdateConversationItem);
            }
            this.contacts.unshift(newConversation);
          });
        }
      } catch (error) {
        console.log("error", error);
      }
    },
    //清空会话已读条数
    clearReadMount(conversationId) {
      EMClient.localCache
        .clearConversationUnreadCount({
          conversationId,
          conversationType: "singleChat"
        })
        .then(() => {
          this.contacts.forEach((contact: any) => {
            if (contact.conversationId === conversationId) {
              contact.unReadCount = 0;
            }
          });
        })
        .catch(err => {
          console.log("清除已读失败", err);
        });
    },
    //订阅好友的在线状态
    subFriendsPresence: async (state, users) => {
      const requestTask: object[] = [];
      const usersArr = _.chunk([...users], 100); //分拆users 订阅好友状态一次不能超过100个
      try {
        usersArr.length > 0 &&
          usersArr.map(userItem =>
            requestTask.push(
              EMClient.subscribePresence({
                usernames: userItem,
                expiry: 30 * 24 * 3600
              })
            )
          );
        const resultData = await Promise.all(requestTask);
        const usersPresenceList = _.flattenDeep(_.map(resultData, "result")); //返回值是个二维数组，flattenDeep处理为一维数组
        const tobeCommitRes = usersPresenceList.length > 0 && usersPresenceList.filter(p => p.uid !== "");
        state.onLineStatus = [...state.onLineStatus, ...tobeCommitRes];
      } catch (error) {}
    },
    //取消订阅
    unSubFriendsPresence: async (state, user) => {
      try {
        const option = {
          usernames: [user]
        };
        const res = await EMClient.unsubscribePresence(option);
        console.log(res);
      } catch (error) {
        console.error("取消订阅好友状态失败", error);
      }
    },
    handlePresenceChanges: (state, status) => {
      const { userId } = status || {};
      if (userId === EMClient.user) {
        console.log("当前用户在线状态变化");
      } else {
        state.onLineStatus.map(item => {
          if (item.uid === userId) {
            item.status = status.statusDetails;
          }
        });
      }
    }
  },
  persist: piniaPersistConfig("imState", ["contacts", "userInfo", "historyMessages", "usersInfosObj"])
});
